package com.hyt.it.ogt.kq.common.convert;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.google.common.collect.Lists;

import java.util.List;

/**
 * @program: hyt-infra
 * @description: 自定义集合字符串转换器
 * @author: Yang HuanKun
 * @create: 2023-10-30 15:17
 **/
public class CustomListToStringConverter implements Converter<List<String>> {

    private final static String STR_JOIN_SYMBOL = StrPool.COMMA;

    @Override
    public Class<String> supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * 这里是读的时候会调用
     *
     * @param cellData            NotNull
     * @param contentProperty     Nullable
     * @param globalConfiguration NotNull
     * @return
     */
    @Override
    public List<String> convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty,
                                          GlobalConfiguration globalConfiguration) {
        String stringValue = cellData.getStringValue();
        if (StrUtil.isBlank(stringValue)) {
            return Lists.newArrayList();
        }
        return StrUtil.split(stringValue, STR_JOIN_SYMBOL);
    }

    /**
     * 这里是写的时候会调用
     *
     * @param value               NotNull
     * @param contentProperty     Nullable
     * @param globalConfiguration NotNull
     * @return
     */
    @Override
    public WriteCellData<String> convertToExcelData(List<String> value, ExcelContentProperty contentProperty,
                                                    GlobalConfiguration globalConfiguration) {
        String joinStr = CollUtil.join(value, STR_JOIN_SYMBOL);
        return new WriteCellData<String>(joinStr);
    }
}
